/**
 * Copyright (C) 2008 Happy Fish / YuQing
 * <p>
 * FastDFS Java Client may be copied only under the terms of the GNU Lesser
 * General Public License (LGPL).
 * Please visit the FastDFS Home Page http://www.csource.org/ for more detail.
 */

package cc.siyecao.fastdfs.uploader;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * upload file callback class, local file sender
 *
 * @author Happy Fish / YuQing
 * @version Version 1.0
 */
public class FileUploader implements Uploader {
    private File file;

    public FileUploader(File file) {
        this.file = file;
    }

    /**
     * send file content callback function, be called only once when the file uploaded
     *
     * @param out output stream for writing file content
     * @return 0 success, return none zero(errno) if fail
     */
    @Override
    public int upload(OutputStream out) throws IOException {
        int readBytes;
        byte[] buff = new byte[256 * 1024];
        FileInputStream fis = new FileInputStream( this.file );
        try {
            while ((readBytes = fis.read( buff )) >= 0) {
                if (readBytes == 0) {
                    continue;
                }
                out.write( buff, 0, readBytes );
            }
        } finally {
            fis.close();
        }
        return 0;
    }
}
